﻿using BCCommon;
using BCEntity.Common.News.ContentCategory;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace BCData.Common.News.ContentCategory
{
    /// <summary>
    /// 内容分类数据处理
    /// </summary>
    public class ContentCategoryData : IContentCategoryData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM contentcategory";
        private const string QUERY = @"SELECT ContentCategoryId,CategoryName,CategoryUrlName,ParentCategoryId,CategoryLevel,CategoryIndex,CreateTime,IsSystem,Enabled FROM contentcategory";
        public ContentCategoryData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }

        #region 检查内容分类是否存在
        public async Task<bool> Exists(int contentCategoryId)
        {
            string sql = string.Format(@"{0} WHERE ContentCategoryId=?ContentCategoryId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ContentCategoryId", contentCategoryId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加内容分类
        public async Task<ContentCategoryEntity> Add(ContentCategoryEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("contentcategory", new string[] { "CategoryName", "CategoryUrlName", "ParentCategoryId", "CategoryLevel", "CategoryIndex" });
            sql = string.Format("{0} {1} WHERE ContentCategoryId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CategoryUrlName", entity.CategoryUrlName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ParentCategoryId", entity.ParentCategoryId, DbType.Int32, size: 11);
            parameters.Add("?CategoryLevel", entity.CategoryLevel, DbType.Int32, size: 11);
            parameters.Add("?CategoryIndex", entity.CategoryIndex, DbType.Int32, size: 11);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<ContentCategoryEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 获取分类列表
        public async Task<IEnumerable<ContentCategoryEntity>> GetList()
        {
            return await this.databaseContext.Slave.QueryAsync<ContentCategoryEntity>(QUERY);
        }
        #endregion

        #region 获取内容分类分页
        public async Task<(IEnumerable<ContentCategoryEntity>, int)> Query(int? categoryLevel, string categoryName, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (categoryLevel.HasValue)
            {
                wheres.Add("CategoryLevel=?CategoryLevel");
                parameters.Add("?CategoryLevel", categoryLevel, DbType.Int32);
            }
            else
            {
                wheres.Add("CategoryLevel=1");
            }
            if (!string.IsNullOrWhiteSpace(categoryName))
            {
                wheres.Add("CategoryName=?CategoryName");
                parameters.Add("?CategoryName", categoryName, DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM contentcategory {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<ContentCategoryEntity, int>(sql, parameters);
        }
        #endregion

        public async Task<ContentCategoryEntity> GetEntity(int contentCategoryId)
        {
            string sql = string.Concat(QUERY, " WHERE ContentCategoryId=?ContentCategoryId");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ContentCategoryId", contentCategoryId, DbType.Int32);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<ContentCategoryEntity>(sql, parameters);
        }

        public async Task<IEnumerable<ContentCategoryEntity>> GetNextCategoryById(int contentCategoryId)
        {
            string sql = string.Concat(QUERY, " WHERE ParentCategoryId=?ContentCategoryId");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ContentCategoryId", contentCategoryId, DbType.Int32);
            return await this.databaseContext.Slave.QueryAsync<ContentCategoryEntity>(sql, parameters);
        }

        public async Task<ContentCategoryEntity> Update(ContentCategoryEntity entity)
        {
            string updateSql = @"UPDATE ContentCategory SET 
                                        CategoryName=?CategoryName,
                                        ParentCategoryId=?ParentCategoryId,
                                        CategoryLevel=?CategoryLevel,
                                        CategoryIndex=?CategoryIndex,
                                        ContentCategoryId=?ContentCategoryId
                                WHERE ContentCategoryId=?ContentCategoryId;";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ContentCategoryId", entity.ContentCategoryId, DbType.Int32);
            var updateResult = await this.databaseContext.Master.ExecuteAsync(updateSql, parameters, databaseContext.Transaction) > 0;

            string newsql = string.Format(@"{0} {1}", updateSql, string.Concat(QUERY, " WHERE ContentCategoryId=?ContentCategoryId"));
            parameters = new DynamicParameters();
            parameters.Add("?CategoryName", entity.CategoryName, DbType.AnsiString);
            parameters.Add("?ParentCategoryId", entity.ParentCategoryId, DbType.Int32);
            parameters.Add("?CategoryLevel", entity.CategoryLevel, DbType.Int32);
            parameters.Add("?CreateTime", DateTime.Now, DbType.DateTime);
            parameters.Add("?CategoryIndex", entity.CategoryIndex, DbType.Int32);
            parameters.Add("?ContentCategoryId", entity.ContentCategoryId, DbType.Int32);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<ContentCategoryEntity>(newsql, parameters);
        }

        public async Task<bool> Delete(int contentCategoryId)
        {
            string newsql = @"DELETE FROM ContentCategory WHERE ContentCategoryId =?ContentCategoryId;";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ContentCategoryId", contentCategoryId, DbType.Int32);
            return await this.databaseContext.Master.ExecuteAsync(newsql, parameters, databaseContext.Transaction) > 0;
        }

        public async Task<bool> CheckContentCategoryExists(string categoryName)
        {
            string sql = @"SELECT 1 FROM ContentCategory WHERE CategoryName=?CategoryName LIMIT 1;";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CategoryName", categoryName, DbType.AnsiString, size: 20);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> CheckContentCategoryExists(int contentCategoryId)
        {
            string sql = @"SELECT 1 FROM ContentCategory WHERE ContentCategoryId=?ContentCategoryId LIMIT 1;";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ContentCategoryId", contentCategoryId, DbType.Int32, size: 11);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<IEnumerable<ContentCategoryEntity>> GetLevelCategoryList(int categoryLevel)
        {
            string sql = string.Concat(QUERY, " WHERE Enabled=1 AND CategoryLevel=?CategoryLevel");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CategoryLevel", categoryLevel, DbType.Int32);
            return await this.databaseContext.Slave.QueryAsync<ContentCategoryEntity>(sql, parameters);
        }

        public async Task<bool> CheckContentCategoryChildrenExists(int contentCategoryId)
        {
            string sql = @"SELECT 1 FROM ContentCategory WHERE ParentCategoryId=?ParentCategoryId LIMIT 1;";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ParentCategoryId", contentCategoryId, DbType.Int32, size: 11);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        #region 启用内容分类
        public async Task<bool> Enabled(int contentCategoryId)
        {
            string sql = @"UPDATE contentcategory SET Enabled=1 WHERE ContentCategoryId=?ContentCategoryId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ContentCategoryId", contentCategoryId, DbType.Int32);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 禁用内容分类
        public async Task<bool> Disabled(int contentCategoryId)
        {
            string sql = @"UPDATE contentcategory SET Enabled=0 WHERE ContentCategoryId=?ContentCategoryId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ContentCategoryId", contentCategoryId, DbType.Int32);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion
    }
}
